"use client"

import { useEffect, useState } from "react"
import { usePlayer } from "@/contexts/player-context"
import { motion } from "framer-motion"

interface LrcLine {
  time: number
  text: string
}

interface LyricsViewProps {
  songId: number
  isUserScrolling: boolean
}

export function LyricsView({ songId, isUserScrolling }: LyricsViewProps) {
  const [lyrics, setLyrics] = useState<LrcLine[]>([])
  const [currentLineIndex, setCurrentLineIndex] = useState(0)
  const {
    state: { progress },
  } = usePlayer()

  useEffect(() => {
    // Mock LRC data
    const lrcContent = `
[00:00.00]爱错 - 王力宏
[00:04.00]词：王力宏/崔惟楷
[00:08.00]曲：王力宏
[00:12.00]北风毫不留情
[00:16.00]把叶子吹落
[00:20.00]脆弱的她选择了逃脱
[00:24.00]叶子失去消息
[00:28.00]风才感觉寂寞
[00:32.00]整个冬天 北风的痛没人能说
[00:36.00]我从来没想过我会这样做
[00:40.00]从来没爱过所以爱错
[00:44.00]我从哪里起飞
`
    const parsedLyrics = lrcContent
      .trim()
      .split("\n")
      .map((line) => {
        const match = line.match(/\[(\d{2}):(\d{2})\.(\d{2})](.*)/)
        if (match) {
          const [, minutes, seconds, centiseconds, text] = match
          const time = Number.parseInt(minutes) * 60 + Number.parseInt(seconds) + Number.parseInt(centiseconds) / 100
          return { time, text }
        }
        return null
      })
      .filter((line): line is LrcLine => line !== null)

    setLyrics(parsedLyrics)
  }, [])

  useEffect(() => {
    if (!isUserScrolling) {
      const currentIndex = lyrics.findIndex((lyric, index) => {
        const nextLyric = lyrics[index + 1]
        if (!nextLyric) return true
        return progress >= lyric.time && progress < nextLyric.time
      })

      if (currentIndex !== -1 && currentIndex !== currentLineIndex) {
        setCurrentLineIndex(currentIndex)
      }
    }
  }, [progress, lyrics, currentLineIndex, isUserScrolling])

  return (
    <div className="px-6 py-4">
      {lyrics.map((lyric, index) => (
        <motion.div
          key={index}
          initial={{ opacity: 0.5 }}
          animate={{
            opacity: index === currentLineIndex ? 1 : 0.5,
            scale: index === currentLineIndex ? 1.05 : 1,
          }}
          transition={{ duration: 0.3 }}
          className={`
            text-center py-4 transition-all
            ${index === currentLineIndex ? "text-2xl font-bold text-white" : "text-lg text-gray-400"}
          `}
        >
          {lyric.text}
        </motion.div>
      ))}
    </div>
  )
}

